package com.bamboo.tool.template.torna.view.dialog;

import cn.hutool.core.collection.CollUtil;
import cn.torna.sdk.client.OpenClient;
import cn.torna.sdk.common.Booleans;
import cn.torna.sdk.param.DocItem;
import cn.torna.sdk.request.DocPushRequest;
import cn.torna.sdk.response.DocPushResponse;
import com.bamboo.tool.config.BambooToolComponent;
import com.bamboo.tool.config.RestfulCloudApplicationCache;
import com.bamboo.tool.entity.ApiClass;
import com.bamboo.tool.entity.ClassOtherInfo;
import com.bamboo.tool.entity.QueryClassParameter;
import com.bamboo.tool.factory.FrameworkExecute;
import com.bamboo.tool.template.torna.entity.*;
import com.bamboo.tool.template.torna.util.RestfulCloudToTornaUtil;
import com.bamboo.tool.template.torna.util.TornaRequestUtil;
import com.bamboo.tool.template.torna.util.TornaUtil;
import com.bamboo.tool.util.DescProcessUtil;
import com.bamboo.tool.util.RequestUtil;
import com.bamboo.tool.view.component.notificationGroup.ToolWindowNotificationGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.MessageType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class UploadTornaDialogWrapper extends DialogWrapper {
    private JPanel mainJPanel;
    private JComboBox projectBox;
    private JComboBox moduleBox;
    private JLabel spaceLabel;
    private JComboBox spaceBox;
    private JComboBox modelBox;

    private QueryClassParameter queryClassParam;

    private Project myProject;
    private List<String> descSorts;

    public UploadTornaDialogWrapper(QueryClassParameter queryClassParam, Project myProject) {
        super(false);
        init();
        initModel();
        TornaUtil.refreshModule(myProject);
        descSorts = FrameworkExecute.getAllDescDort();
        this.queryClassParam = queryClassParam;
        this.myProject = myProject;
        TornaSetting state = RestfulCloudApplicationCache.getInstance().getState().getTornaSetting();
        spaceBox.removeAll();
        state.getSpaces().forEach(spaceBox::addItem);

        spaceBox.addItemListener(e -> {
            if (e.getStateChange() == 1) {
                refreshProject(state);
                refreshModule(state);
            }
        });
        projectBox.addItemListener(e -> {
            if (e.getStateChange() == 1) {
                refreshModule(state);
            }
        });
        refreshProject(state);
        refreshModule(state);
    }

    private void initModel() {
        TornaModel tornaModel = new TornaModel();
        tornaModel.setType(1);
        tornaModel.setName("覆盖");
        TornaModel tornaModel1 = new TornaModel();
        tornaModel1.setType(0);
        tornaModel1.setName("追加");
        modelBox.addItem(tornaModel1);
        modelBox.addItem(tornaModel);
    }

    @Override
    public @Nullable JComponent createCenterPanel() {
        return mainJPanel;
    }

    @Override
    protected void doOKAction() {
        super.doOKAction();
        Task.Backgroundable task = new Task.Backgroundable(myProject, "Restful Cloud Upload Torna") {

            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                indicator.setIndeterminate(false);
                ApplicationManager.getApplication().runReadAction(() -> {
                    indicator.setText("数据加载中");
                    ModuleVO selectedModule = (ModuleVO) moduleBox.getSelectedItem();
                    TornaRespBase<String> modelToken = TornaRequestUtil.getModelToken(selectedModule.getId());
                    TornaSetting state = RestfulCloudApplicationCache.getInstance().getState().getTornaSetting();
                    OpenClient client = TornaRequestUtil.client;
                    if (client == null) {
                        client = new OpenClient(RequestUtil.getUrl(state.getUrl(), "api"));
                    }
                    List<String> allDescDort = FrameworkExecute.getAllDescDort();
                    DocPushRequest request = new DocPushRequest(modelToken.getData());
                    request.setAuthor(state.getUserName());
                    TornaModel selectedItem = (TornaModel) modelBox.getSelectedItem();
                    request.setIsReplace((byte) selectedItem.getType());
                    Collection<ApiClass> apiClass = BambooToolComponent.getStoreService().getApiClass(queryClassParam);
                    List<DocItem> folders = new ArrayList<>();
                    for (ApiClass classz : apiClass) {
                        ClassOtherInfo classOtherInfo = classz.getClassOtherInfo();
                        DocItem folder = new DocItem();
                        folder.setIsFolder(Booleans.TRUE);
                        folder.setName(DescProcessUtil.getClassDesc(classz, allDescDort));
                        folder.setAuthor(classOtherInfo.getAuthor());
                        List<DocItem> items = classz.getMethods().stream().map(e -> RestfulCloudToTornaUtil.methodToDocItemConversion(e, allDescDort)).collect(Collectors.toList());
                        folder.setItems(items);
                        folders.add(folder);
                    }
                    request.setApis(folders);

                    request.setDebugEnvs(new ArrayList<>());
                    indicator.setText("上传开始");
                    DocPushResponse execute = client.execute(request);
                    indicator.setText("上传结束");
                    String code = execute.getCode();
                    if ("0".equals(code)) {
                        ToolWindowNotificationGroup.NOTIFICATION_GROUP.createNotification("Restful Cloud 上传 Torna  成功！", MessageType.INFO).notify(myProject);
                    } else {
                        ToolWindowNotificationGroup.NOTIFICATION_GROUP.createNotification("Restful Cloud 上传 Torna  失败！" + execute.getMsg(), MessageType.ERROR).notify(myProject);
                    }

                });

            }
        };
        ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, new BackgroundableProcessIndicator(task));
    }

    private void refreshModule(TornaSetting state) {
        moduleBox.removeAllItems();
        ProjectDTO selectedProject = (ProjectDTO) projectBox.getSelectedItem();
        if (selectedProject != null) {
            List<ModuleVO> moduleVOS = state.getModules().get(selectedProject.getId());
            if (CollUtil.isNotEmpty(moduleVOS)) {
                moduleVOS.stream().forEach(moduleBox::addItem);
            }
        }

    }

    private void refreshProject(TornaSetting state) {
        projectBox.removeAllItems();
        SpaceDTO selectedItem = (SpaceDTO) spaceBox.getSelectedItem();
        if (selectedItem != null) {
            List<ProjectDTO> projectDTOS = state.getProjects().get(selectedItem.getId());
            if (CollUtil.isNotEmpty(projectDTOS)) {
                projectDTOS.stream().forEach(projectBox::addItem);
            }
        }
    }
}
